
-- 获取参数列表
local uri_args = ngx.req.get_uri_args()
local product_id = uri_args["productId"]
local shop_id = uri_args["shopId"]

-- 获取到之前配置中分配的缓存对象
local product_shop_cache = ngx.shared.product_shop_cache

-- 拼接两个缓存 key
local product_cache_key = "product_info_"..product_id
local shop_cache_key = "shop_info_"..shop_id

-- 通过缓存对象获取缓存中的 value
local product_cache=product_shop_cache:get(product_cache_key)
local shop_cache=product_shop_cache:get(shop_cache_key)

-- 如果缓存中不存在对于的 value
-- 就走后端缓存服务获取数据
if product_cache=='' or product_cache==nil then 
     
	 local http = require("resty.http")
	 local http_client = http.new()
	 -- 这里直接访问本地环境比较方便
	 local resp, err = httpc:request_uri("http://192.168.60.103:8888",{
  		method = "GET",
  		path = "/getProductInfo?productId="..product_id,
      keepalive=false
	})
	
	product_cache = resp.body
    -- 获取到之后，再设置到缓存中
	product_shop_cache:set(product_cache_key, product_cache, 10 * 60)

end 

if shop_cache=='' or shop_cache==nil then 
     
	 local http = require("resty.http")
	 local http_client = http.new()
	 -- 这里直接访问本地环境比较方便
	 local resp, err = httpc:request_uri("http://192.168.60.103:8888",{
  		method = "GET",
  		path = "/getShopInfo?shopId="..shop_id,
        keepalive=false
	})
	
	shop_cache = resp.body
    -- 获取到之后，再设置到缓存中
	product_shop_cache:set(shop_cache_key, shop_cache, 10 * 60)

end 

-- 因为存到缓存中是一个字符串,所以使用 cjson 库把字符串转成 json 对象
local cjson = require("cjson")
local product_info_json = cjson.decode(product_cache)
local shop_info_json = cjson.decode(shop_cache)

-- 把商品信息和店铺信息拼接到一个大 json 对象中,这样做的原因是：template 渲染需要这样做

local context = {
    productId = product_info_json.id,
	productName = product_info_json.name,
	productPrice = product_info_json.price,
	productPictureList = product_info_json.pictureList,
	productSpecification = product_info_json.specification,
	productService = product_info_json.service,
	productColor = product_info_json.color,
	productSize = product_info_json.size,
	shopId = shop_info_json.id,
	shopName = shop_info_json.name,
	shopLevel = shop_info_json.level,
	shopGoodCommentRate = shop_info_json.goodCommentRate
}

-- 使用 template 渲染 product.html 模板
local template = require("restry.template")
template.render("product.html", context)


